<?php

namespace App\Jobs;
use App\Models\Circle;
use App\Models\Subscribe;
use App\Models\UserJoinCircle;
use App\Services\PublishTemplateService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ActivityCountdownJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $circle_id;

    /**
     * Create a new job instance.
     * PublishLotteryJob constructor.
     * @param $circle_id
     */
    public function __construct($circle_id)
    {
        $this->circle_id = $circle_id;
    }

    /**
     * Execute the job.
     * @link https://shimo.im/mindmaps/y6ydprxxxJKCggPx/
     * @return void
     */
    public function handle()
    {
        $tomorrow = date("Y-m-d",strtotime("+1 day"));
        $tomorrow_start = $tomorrow . " 00:00:01";
        $tomorrow_end_at = $tomorrow . " 23:59:59";
        $activity_list = Circle::where('is_activity', 1)->where('activity_end_at', '>=', $tomorrow_start)->where('activity_end_at', '<=', $tomorrow_end_at)->get();
        if ($activity_list) {
            foreach ($activity_list as $activity_item) {
                Subscribe::where('type', Subscribe::TYPE_ACTIVITY_COUNT_DOWN)->withCertain('user', ['openid'])->chunkById(50, function ($list) use($activity_item) {
                    foreach ($list as $item) {
                        //check weather join or not
                        $exists = UserJoinCircle::where('user_id', $item->user_id)->where('circle_id', $activity_item->id)->where('is_activity', 1)->exists();
                        if ($exists) {
                            $sql = 'SELECT id,user_id,activity_star_num,
(SELECT count(DISTINCT activity_star_num) FROM articles AS b WHERE activity_id = '.$activity_item->id.' and deleted_at is null and a.activity_star_num<b.activity_star_num)+1 AS rank 
FROM articles AS a where activity_id = '.$activity_item->id.' and deleted_at is null ORDER BY rank';

                            $res = \DB::select($sql);
                            foreach ($res as $v) {
                                if ($v->user_id == $item->user_id) {
                                    $service = new PublishTemplateService();
                                    $service->activity_countdown($item->user->openid, $activity_item->title, $activity_item->id, $v->rank);
                                    $item->delete();
                                    break;
                                }
                            }
                        }
                    }
                });
            }
        }

    }
}
